package com.cty._02_HighQualityCode._16_Power;

/**
 * @Auther: cty
 * @Date: 2020/7/4 11:37
 * @Description:
 * @version: 1.0
 */
public class Power {

    public static boolean hasInvalidInput = false;

    public static double power(int mode, double base, int exponent){
        if((int)base==0 && (exponent<0)){
            hasInvalidInput = true;
            return 0.0;
        }

        int absExponent = exponent;
        if(exponent < 0)
            absExponent = -exponent;

        double result = 1.0;
        if(mode == 1)
            result = powerWithUnsignedExponent01(base, absExponent);
        else if(mode == 2)
            result = powerWithUnsignedExponent02(base, absExponent);

        if(exponent < 0)
            result = 1.0/result;

        return result;
    }  // end power01()

    /**
     * 计算一个数的非负次幂——循环法
     * @param base 负整数 0 正整数
     * @param absExponent 0 正整数
     * @return
     */
    private static double powerWithUnsignedExponent01(double base, int absExponent){
        double result = 1.0;
        for(int i=1; i<=absExponent; i++){
            result *= base;
        }
        return result;
    }

    /**
     * 计算一个数的非负次幂——递归
     * @param base 负整数 0 正整数
     * @param absExponent 0 正整数
     * @return
     */
    public static double powerWithUnsignedExponent02(double base, int absExponent){
        if(absExponent == 0)
            return 1.0;
        if(absExponent == 1)
            return base;

        double result = powerWithUnsignedExponent02(base, absExponent>>1);
        result *= result;
        if((absExponent&0x01) == 1)
            result *= base;

        return result;
    }  // end power02()

}  // end class
